$(document).ready(function() {
	mui.init();
	mui.plusReady(function() {
		Bluetooth();
		var pay_type = '';
		var wx = plus.webview.currentWebview();
		var signx = false;
		var overTime = '退款失败，请稍后再试';
		// 获取phone
		require(weburl + adminPhone, "json", "get", {
			token: localStorage.getItem("token"),
			out_order_no: wx.orderNum
		}, function(response) {
			if(response.code == "10001") {
				 console.log(JSON.stringify(response));
				 console.log(JSON.stringify(response.data.phone));
				 var defaultPhone = response.data.phone;
				 localStorage.setItem('adminPhone', defaultPhone)
			} else {
				alert(response.msg);
			}
			
	
		}, function(xhr) {
			console.log('测试', weburl + adminPhone)
			console.log(xhr);
		})
		//查询是否
		require(weburl + apiIsOut, "json", "post", {
			token: localStorage.getItem("token"),
			out_order_no: wx.orderNum
		}, function(e) {
			console.log(JSON.stringify(e));
			// pay_type = e.data.is_bank;
			
// 			var defaultPhone = e.data.phone;
// 			localStorage.setItem('adminPhone', defaultPhone);
			pay_type = e.data.bank;
// 			var defaultPhone = e.data.phone;
// 			localStorage.setItem('adminPhone', defaultPhone);
			if (e.data.status && (e.data.status == 1)) {
				overTime = 1;
			} else if (e.data.status && e.data.status == 2) {
				overTime = 2;
				console.log(overTime);
			} else {
				overTime = e.msg;
			}
		}, function(xhr) {
			console.log(JSON.stringify(xhr));
		})

		// 点击图形验证码
		var imgCodeTime = false;
		mui('body').on('tap', '.tcode', function() {
			if (imgCodeTime == true) {
				return false;
			}
			$(this).attr('src', weburl + Captcha + '?id=' + Math.random() * 100);
			imgCodeTime = true;
			setTimeout(function() {
				imgCodeTime = false;
			}, 3000)
		})

		//点击退款按钮
		mui("body").on("tap", ".submit", function() {

			$(".bz, .contents, .price").blur();
			//如果密码不为空
			if ($("#payPwd").val() && $(".price").val() && $(".bz").val()) {



				var res = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
				if (!res.test($(".price").val())) {
					mui.alert("<h5 style='padding:25px;margin:0;'>消费金额格式不正确，请重新输入</h5>", " ", "关闭", function() {}, "div");
					return false;
				}
				var conf =
					"<p class='returnTitle' style='text-align:center;'><span class='mui-icon mui-icon-info'></span>警告！</p>";
				conf += "<p style='font-size:16px;text-align:center;'>退回金额：<span style='font-size:18px;color:red;'>" + $(
					".price").val() + "<span>元</p>";
				conf += "<p style='font-size:16px;text-align:center;color:red;'>请确认金额是否与实际退款金额一致？</p>";
				conf +=
					"<p style='text-align:center;margin-top:15px;font-size:16px;color:#F0AD4E;margin-bottom:0;padding-bottom:10px;'>一旦操作，资金将无法被追回</br>请谨慎操作</p>";
				if (overTime == 2) {
					conf +=
						"<div class='code-phone'><input class='t_code' type='text' value=''><img style='width: 150px;' class='tcode' src='" +
						weburl + Captcha + '?id=' + Math.random() * 100 + "'></div>";
					conf +=
						"<div class='code-phone'><input class='code_xx' type='number' value=''><button class='mui-btn mui-btn-warning code'>验证码</button></div>";
				}
				mui.confirm(conf, " ", ["确认", "取消"], function(e) {

					var code = $(".code_xx").val();
					if (e.index == 0) { //如果选择了确定按钮
						if (($(".price").val() * 1 <= wx.refundPrice * 1) && ($(".price").val() * 1 > 0) && (code != "")) {
							if (overTime != 1 && overTime != 2) {
								mui.alert(overTime, "<h5 style='padding:10px;margin:0;'>提示</h5>", "关闭", function() {}, "div");
								return false;
							}
							plus.nativeUI.showWaiting("正在退款，请勿退出...");
							//如果是正常订单 
							if (overTime == 1) {
								//如果是银行卡的正常订单
								if (pay_type == 1) {
									console.log(wx.orderNum);
									require(weburl + BankOrderRefundCreate, "json", "post", {
										token: localStorage.getItem("token"),
										amount: $(".price").val(),
										remark: $(".bz").val(),
										paystr: $("input[type='password']").val(),
										orderid: wx.orderNum
									}, function(auth_res) {
										plus.nativeUI.closeWaiting();
										if (auth_res.status == "success") {
											plus.nativeUI.showWaiting("正在跳转...");
											setTimeout(function() {
												plus.nativeUI.closeWaiting();
												//调用sdk
												bs_pay({
													'token': localStorage.getItem("token"),
													"amount": auth_res.data[0].amount,
													"barcodeType": "0",
													"orderInfo": $(".bz").val(),
													"orderNoSFT": auth_res.data[0].out_trade_no,
													"transDate": auth_res.data[0].transDate,
													"traceNo": auth_res.data[0].traceNo,
													"authNo": auth_res.data[0].authNo,
													"payCallUrl": callbackUrl,
													'remark': auth_res.data[0].remark ? auth_res.data[0].remark : ''
												}, "2");
												window.location.reload();
											}, 1500)

											return false;
										}
										mui.alert(auth_res.msg, "", "关闭", function() {}, "div");
									}, function() {
										plus.nativeUI.closeWaiting();
										mui.alert("网络错误，请稍后再试", "", "关闭", function() {}, "div");
									})
									return false;
								} else {
									//如果是非银行卡正常订单
									require(weburl + modelPay, "json", "post", {
										paypwd: $("input[type='password']").val(),
										token: localStorage.getItem("token"),
										out_trade_no: wx.orderNum,
										id: "null",
										bz: $(".bz").val(),
										amount: $(".price").val()
									}, function(response) {
										//显示交易结果
										if (response.status == "1") {
											var str = response.print_body;
											var reg = /\\n/g;
											str = str.replace(reg, '\n');
											printTicket(response.print_array);
											//关闭等待框
											plus.nativeUI.closeWaiting();
											//											ticket(response.store_name, str, response.out_trade_no);
											mui.confirm("<h5 style='padding:25px;margin:0;'>交易成功，是否打印小票</h5>", " ", ["打印", "关闭"], function(x) {
												console.log(x.index);
												if (x.index == 0) {
													console.log(1);
													if (signx == false) {
														printTicket(response.print_array);
														//														ticket(response.store_name, str, response.out_trade_no);
														signx = true;
														setTimeout(function() {
															signx = false;
														}, 3000);
													}
													return false;
												} else {
													//													back();
													window.location.reload();
												}
											}, "div")
										} else {
											plus.nativeUI.closeWaiting();
											mui.alert("<h5 style='padding:25px;margin:0;'>" + response.msg + "</h5>", " ", "关闭", function() {
												window.location.reload();
											}, "div");
										}
									}, function() {
										plus.nativeUI.closeWaiting();
										mui.alert("<h5 style='padding:25px;margin:0;'>退款失败，请稍后再试</h5>", " ", "关闭", function() {
											window.location.reload();
										}, "div");
									})
									return false;
								}
							}

							//如果是银行卡超时订单
							if (pay_type == 1) {
								console.log(pay_type);
								require(weburl + BankOrderRefundCreate, "json", "post", {
									token: localStorage.getItem("token"),
									amount: $(".price").val(),
									remark: $(".bz").val(),
									paystr: $("input[type='password']").val(),
									orderid: wx.orderNum,
									verifystr: code
								}, function(auth_res) {
									plus.nativeUI.closeWaiting();
									if (auth_res.status == "success") {
										plus.nativeUI.showWaiting("正在跳转...");
										setTimeout(function() {
											plus.nativeUI.closeWaiting();
											//调用sdk
											bs_pay({
												'token': localStorage.getItem("token"),
												"amount": auth_res.data[0].amount,
												"barcodeType": "0",
												"orderInfo": $(".bz").val(),
												"orderNoSFT": auth_res.data[0].out_trade_no,
												"transDate": auth_res.data[0].transDate,
												"traceNo": auth_res.data[0].traceNo,
												"authNo": auth_res.data[0].authNo,
												"payCallUrl": callbackUrl,
												'remark': auth_res.data[0].remark ? auth_res.data[0].remark : ''
											}, "2");
											window.location.reload();
										}, 1500)

										return false;
									}
									mui.alert(auth_res.msg, "", "关闭", function() {}, "div");
								}, function() {
									plus.nativeUI.closeWaiting();
									mui.alert("网络错误，请稍后再试", "", "关闭", function() {}, "div");
								})
								return false;
							} else {
								//如果是非银行卡超时订单
								console.log(pay_type);
								console.log(33);
								require(weburl + outTime, "json", "post", {
									token: localStorage.getItem("token"),
									verifystr: code,
									out_trade_no: wx.orderNum,
									Refundtype: 1,
									paystr: $("input[type='password']").val(),
									amount: $(".price").val()
								}, function(response) {
									console.log(JSON.stringify(response));
									console.log(44);
									//显示交易结果
									if (response.status == "success") {
										var str = response.data[0].print_body;
										var reg = /\\n/g;
										str = str.replace(reg, '\n');
										printTicket(response.data[0].print_array);
										//关闭等待框
										plus.nativeUI.closeWaiting();
										//										ticket(response.data[0].store_name, str, response.data[0].out_trade_no);
										mui.confirm("<h5 style='padding:25px;margin:0;'>退款成功，是否打印小票</h5>", " ", ["打印", "关闭"], function(e) {
											if (e.index == 0) {
												console.log(1);
												if (signx == false) {
													printTicket(response.data[0].print_array);
													//													ticket(response.data[0].store_name, str, response.data[0].out_trade_no);
													signx = true;
													setTimeout(function() {
														signx = false;
													}, 3000);
												};
												return false;
											} else {
												console.log(1);
												//												back();
												// window.location.reload();
											}
										}, "div")
									} else {
										//关闭等待框
										plus.nativeUI.closeWaiting();
										mui.alert("<h5 style='padding:25px;margin:0;'>" + response.msg + "</h5>", " ", "关闭", function() {
											window.location.reload();
										}, "div");
									}
								}, function(xhr) {
									plus.nativeUI.closeWaiting();
									mui.alert("<h5 style='padding:25px;margin:0;'>退款失败，请稍后再试</h5>", " ", "关闭", function() {
										window.location.reload();
									}, "div");
									console.log(55);
								})

							}
						} else if (!code && overTime == 2) {
							console.log(66);
							mui.alert("<h5 style='padding:25px;margin:0;'>验证码不能为空！</h5>", " ", "确认", function() {
								window.location.reload();
							}, "div");
						} else {
							mui.alert("<h5 style='padding:25px;margin:0;'>退款金额不能大于订单金额</h5>", " ", "确认", function() {
								window.location.reload();
							}, "div");
						}
					}
				}, "div");
			} else if (!$(".price").val()) { //如果交易密码为空
				mui.alert("<h5 style='padding:25px;margin:0;'>退款金额不能为空</h5>", " ", "确认", function() {}, "div");
			} else if (!$(".bz").val()) { //如果交易密码为空
				mui.alert("<h5 style='padding:25px;margin:0;'>备注信息不能为空</h5>", " ", "确认", function() {}, "div");
			} else if (!$("#payPwd").val()) { //如果交易密码为空
				mui.alert("<h5 style='padding:25px;margin:0;'>支付密码不能为空</h5>", " ", "确认", function() {}, "div");
			}
		})
		mui("body").on("tap", ".setting", function() { //点击设置，跳转至设置支付密码页面
			mui.openWindow("../view/payPassword.html", "payPassword");
		})
		var time_j = 60;
		mui("body").on("tap", ".code", function() {
			var that = $(this);
			var timeTerval;
			that.attr("disabled", "disabled");
			time_j--;
			that.html(time_j + "s");
			if (time_j === 59) {
				timeTerval = setInterval(function() {
					if (time_j > 0) {
						// console.log(time_j);
						that.html(time_j + "s");
						time_j--;
						return false;
					}
					clearInterval(timeTerval);
					time_j = 60;
					that.html("验证码");
					that.removeAttr("disabled");
				}, 1000);
			}
			console.log($('.t_code').eq(0).val());
			mui.confirm("<div style='padding:15px 12px;'>将发送验证码至" + localStorage.getItem("adminPhone") + "</div>", ' ', [
				'发送', '取消'
			], function(ev) {
				if (ev.index == 0) {
					require(weburl + model_sendY, "json", "post", {
						phone: localStorage.getItem("adminPhone"),
						token: localStorage.getItem("token"),
						validate: $('.t_code').eq(0).val()
					}, function(response) {
						console.log(JSON.stringify(response));
						if (response.status != 'success') {
							clearInterval(timeTerval);
							time_j = 60;
							that.html("验证码");
							that.removeAttr("disabled");
							mui.alert("<h5 style='padding:25px;margin:0;'>" + response.msg + "</h5>", " ", "确认", function() {},
								"div");
						}
						console.log(1);
					}, function(xhr) {
						console.log(JSON.stringify(xhr));
						clearInterval(timeTerval);
						time_j = 60;
						that.html("验证码");
						that.removeAttr("disabled");
					})
				} else {
					time_j = 60;
					that.html("验证码");
					that.removeAttr("disabled");
				}
			}, "div")

		})
	})
	

})
